using UnityEngine;

namespace VoxelEngine.Utils
{
	public class SoundManager : MonoBehaviour
	{
		public bool _enableSFX = true;

		public int _sfxChannelsNumber = 5;

		public float _sfxVolume = 1f;

		private AudioSource[] _sfxChannel;

		private float[] _sfxChannelTimeStamp;

		private static SoundManager _instance;

		public static SoundManager Instance => _instance;

		private void Awake()
		{
			_instance = this;
			_sfxChannel = new AudioSource[_sfxChannelsNumber];
			_sfxChannelTimeStamp = new float[_sfxChannelsNumber];
			for (int i = 0; i < _sfxChannelsNumber; i++)
			{
				_sfxChannel[i] = (base.gameObject.AddComponent(typeof(AudioSource)) as AudioSource);
				_sfxChannel[i].volume = _sfxVolume;
			}
		}

		private void OnDestroy()
		{
			_instance = null;
		}

		public AudioSource PlaySoundEffect(AudioClip clip, float volume = 1f)
		{
			if (_enableSFX && (bool)clip)
			{
				int i = 0;
				int num = 0;
				for (; i < _sfxChannelsNumber; i++)
				{
					if (i < _sfxChannel.Length && !_sfxChannel[i].isPlaying)
					{
						_sfxChannel[i].Stop();
						_sfxChannel[i].clip = clip;
						_sfxChannel[i].loop = false;
						_sfxChannel[i].Play();
						_sfxChannel[i].volume = _sfxVolume * volume;
						_sfxChannelTimeStamp[i] = Time.time;
						return _sfxChannel[i];
					}
					if (num < _sfxChannel.Length && i < _sfxChannel.Length && _sfxChannel[num].priority >= _sfxChannel[i].priority && _sfxChannelTimeStamp[num] > _sfxChannelTimeStamp[i])
					{
						num = i;
					}
				}
				if (num < _sfxChannel.Length && i < _sfxChannel.Length && i == _sfxChannelsNumber)
				{
					_sfxChannel[num].Stop();
					_sfxChannel[num].clip = clip;
					_sfxChannel[num].loop = false;
					_sfxChannel[num].Play();
					_sfxChannel[i].volume = _sfxVolume * volume;
					_sfxChannelTimeStamp[num] = Time.time;
					return _sfxChannel[num];
				}
			}
			return null;
		}

		public void StopSFX(AudioClip audioToStop)
		{
			for (int i = 0; i < _sfxChannelsNumber; i++)
			{
				if (_sfxChannel[i].clip == audioToStop)
				{
					_sfxChannel[i].Stop();
				}
			}
		}

		public void StopAllSFX()
		{
			for (int i = 0; i < _sfxChannelsNumber; i++)
			{
				_sfxChannel[i].Stop();
				_sfxChannel[i].clip = null;
			}
		}
	}
}
